using System;
using System.Xml;

namespace FreeFlow.Client
{
	/// <summary>
	/// An attachment field.
	/// </summary>
	/// <example>
	/// The following example shows how to attach a file to an attachment field on a form. 
	/// This assumes the use of a HtmlInputFile ASP.NET control, but you could use 
	/// any Stream-based data. The example assumes there is a map called 'Map1' with a creation 
	/// action called 'First action' that uses a form with an attachment field called 'attach'.
  /// <code language="c#">
  /// Connection conn = new Connection(); 
  /// ActionPage page = new ActionPage(); 
  /// conn.Login("username", "password"); 
  /// page.Connection = conn; 
  /// page.StartBlankForm("Map1", "First action"); 
  /// AttachmentField clip = page.Form.Field("attach") as AttachmentField; 
  ///
  /// // uploadedFile is a HtmlInputFile control 
  /// byte[] data = new byte[uploadedFile.PostedFile.InputStream.Length]; 
  /// uploadedFile.PostedFile.InputStream.Read(data, 0, (int) uploadedFile.PostedFile.InputStream.Length); 
  ///
  /// // get just the filename 
  /// string fileName = uploadedFile.PostedFile.FileName; 
  /// int indexOfSlash = fileName.LastIndexOf("\\"); 
  /// clip.Value = fileName.Substring(indexOfSlash+1, fileName.Length-indexOfSlash-1); 
  /// 
  /// clip.Attachment = data; 
  ///
  /// page.Submit(); 
	/// </code>
  /// </example>
	[Serializable]
	public class AttachmentField : Field
	{
    internal AttachmentField(Form form, XmlElement fieldNode)
      : base(form, fieldNode)
		{
      if (fieldNode != null)
        caption = fieldNode.GetAttribute("Caption");
		}

    #region properties

    private string caption;
    /// <summary>
    /// Gets the caption displayed in the attachment.
    /// </summary>
    public string Caption
    {
      get
      {
        return caption;
      }
    }

    /// <summary>
    /// Gets or sets the attachment data.
    /// </summary>
    public byte[] Attachment
    {
      get
      {
        CheckConnection();
        return Connection.GetAttachment(AttachmentType.Folder, Value, Form.Page.FolderId);
      }
      set
      {
        Value = Connection.SetAttachment(Value, Form.Page.FolderId, value);
      }
    }

    #endregion

    /// <summary>
    /// Saves the attachment to a file.
    /// </summary>
    /// <param name="fileName">Name of the file to save to.</param>
    public void SaveToFile(string fileName)
    {
      CheckConnection();
      Connection.SaveAttachmentToFile(AttachmentType.Folder, Value, Form.Page.FolderId, fileName);
    }
	}
}
